<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button  class="filter-item" type="primary" icon="el-icon-refresh" @click="handleRefresh">
        刷新
      </el-button>
      <el-input v-model="listQuery.searchMsg" placeholder="搜索内容" style="width: 200px;" class="filter-item filter-input" @keyup.enter.native="handleFilter" />
      <el-button  class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-button class="filter-item add" style="margin-left: 10px;" type="primary" icon="el-icon-circle-plus-outline" @click="handleCreate">
        添加
      </el-button>

    </div>
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row

    >
      <el-table-column align="center" label="ID" width="95" >
        <template slot-scope="scope">
          {{ scope.row.id }}
        </template>
      </el-table-column>
      <el-table-column label="用户名" align="center">
        <template slot-scope="scope">
          {{ scope.row.username }}
        </template>
      </el-table-column>
      <el-table-column label="名称" width="180" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="角色"  width="180" prop="adminRoles" align="center">
        <template slot-scope="scope">
          {{ scope.row.adminRoles }}



        </template>
      </el-table-column>
      <el-table-column label="权限" width="110" align="center">
        <template slot-scope="scope">
          {{ scope.row.pageviews }}
        </template>
      </el-table-column>
      <el-table-column class-name="status-col" label="状态" width="110" align="center">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            active-color="#13ce66"
            @change="handleStatus(scope.row)"
            >
          </el-switch>

          <!-- <el-tag :type="scope.row.status | statusFilter">{{ scope.row.status }}</el-tag> -->
        </template>
      </el-table-column>
      <el-table-column align="center" prop="created_at" label="创建时间" width="200">
        <template slot-scope="scope">
          <i class="el-icon-time" />
          <span>{{ scope.row.created_at }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="updated_at" label="更新时间" width="200">
        <template slot-scope="scope">
          <i class="el-icon-time" />
          <span>{{ scope.row.updated_at }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button  size="mini" type="danger" @click="handleDelete(row,$index)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="fetchData" />

    <el-dialog :title="title" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="Form" label-position="left" label-width="70px" style="width: 400px; margin-left:50px;">

        <el-form-item label="用户名" prop="username">
          <el-input v-model="Form.username" />
        </el-form-item>
        <el-form-item label="账户名" prop="name">
          <el-input v-model="Form.name" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="Form.password" show-password/>
        </el-form-item>

        <el-form-item label="角色" prop="roleId" >
          <el-select v-model="Form.roleId" class="filter-item" placeholder="请选择">
            <el-option v-for="item in roles" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          提交
        </el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { getList } from '@/api/table'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import {List , Add, Update,Delete ,AdminRolesAll,RolesUpdate,RolesAdd} from '@/api/admin/admin'
import { title } from '@/settings'
export default {
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'gray',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  components: { Pagination },
  data() {
    return {
      list: null,
      listLoading: true,
      total:0,
      listQuery: {
        page: 1,
        limit: 10,
        searchMsg:""
      },
      dialogFormVisible:false,
      dialogStatus:"create",
      title:"",
      rules:{
        name: [
          { required: true, message: '请输入账户名', trigger: 'blur' }
        ],
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ],
        roleId: [
          { required: true, message: '请选择角色', trigger: 'change' }
        ],
      },
      Form:{
        id:null,
        name:"",
        username:"",
        roleId:null,
        password:""

      },
      roles:null
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    fetchData() {
      this.listLoading = true
      List(this.listQuery).then(response => {
        let list = response.data.list
        for(let i=0; i<list.length;i++){
          if(list[i].adminRoles){
            list[i]['adminRolesId'] = list[i].adminRoles.id
            list[i].adminRoles = list[i].adminRoles.name
          }
        }
        const data = list
        this.list = data
        this.total = response.data.queryTotal
        this.listQuery.page = response.data.page
        setTimeout(() => {
          this.listLoading = false
        }, 0.3 * 1000)
      })
      AdminRolesAll().then(response =>{
        this.roles = response.data
      })
    },
    getList() {
      this.listLoading = true
      List(this.listQuery).then(response => {
        let list = response.data.list
        for(let i=0; i<list.length;i++){
          if(list[i].adminRoles){
            list[i]['adminRolesId'] = list[i].adminRoles.id
            list[i].adminRoles = list[i].adminRoles.name
          }
        }
        const data = list
        this.list = data
        this.total = response.data.queryTotal
        this.listQuery.page = response.data.page
        setTimeout(() => {
          this.listLoading = false
        }, 0.3 * 1000)
      })
    },
    handleFilter(){
      //搜索
      this.listQuery.page = 1
        this.listQuery.searchMsg = this.listQuery.searchMsg.trim()
      this.fetchData()
    },
    handleCreate(){
      //新增
      this.dialogFormVisible = true
      this.title = "添加"
      this.dialogStatus ='create'
      this.Form={
          id:null,
          name:"",
          username:"",
          roleId:null,
          password:""

        }
    },
      handleUpdate(row){
        //编辑
        this.dialogFormVisible = true
        this.title = "修改"
        this.dialogStatus ='update'
        this.Form={
          id:row.id,
          name:row.name,
          username:row.username,
          roleId:row.adminRolesId,
          password:row.password

        }
        console.log(row)
        console.log(this.Form)
    },
    handleDelete(row,index){
      //删除
      this.$confirm('确认删除？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          Delete({id:row.id}).then(() => {
            this.$notify({
              title: 'Success',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
            this.list.splice(index, 1)
          })
        }).catch(() => {
        });
    },
    handleRefresh(){
      //列表刷新
      this.fetchData()
    },
    handleStatus(row){
      //更改状态
      console.log(row)
    },
    createData(){
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          Add(this.Form).then((response) => {
            let data = {
              roleId :this.Form.roleId,
              userId:response.data
            }
            RolesAdd(data).then(() => {
              this.dialogFormVisible = false
              this.fetchData()
              this.$notify({
                title: 'Success',
                message: '修改成功',
                type: 'success',
                duration: 2000
              })
            })
          })
        }
      })
    },
    updateData(){
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          Update(this.Form).then(() => {
            let data = {
              roleId :this.Form.roleId,
              userId:this.Form.id
            }
            RolesUpdate(data).then(() => {
              this.dialogFormVisible = false
              this.fetchData()
              this.$notify({
                title: 'Success',
                message: '修改成功',
                type: 'success',
                duration: 2000
              })
            })
          })

        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.filter-container{
  .filter-item{
    margin-bottom: 10px;
  }
  .filter-input{
    margin-left:  20px;
  }
  .add{
    float: right;
  }
}
</style>
